package me.gacl.websocket.example;

import org.java_websocket.WebSocket;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Collections;
import java.util.UUID;

/**
 * WebSocket服务器端处理类,使用的是开源项目Java-WebSocket作为实现方案
 * https://github.com/TooTallNate/Java-WebSocket
 * Created by 孤傲苍狼 on 2016/2/18.
 */
public class ChatServer extends WebSocketServer {

    //记录WebSocket客户端连接数
    private static int counter = 0;

    public ChatServer() throws UnknownHostException {

    }

    public ChatServer(int port, Draft d) throws UnknownHostException {
        super(new InetSocketAddress(port), Collections.singletonList(d));
    }

    public ChatServer(InetSocketAddress address, Draft d) {
        super(address, Collections.singletonList(d));
    }

    public ChatServer(int port) throws UnknownHostException {
        super(new InetSocketAddress(port));
    }

    public ChatServer(InetSocketAddress address) {
        super(address);
    }

    @Override
    public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
        counter++;
        String id = UUID.randomUUID().toString();
        webSocket.send(id);
        sendToAll(webSocket.getRemoteSocketAddress().getAddress().getHostAddress()
                + " 连接上WebSocket服务器 ！,当前在线人数为::" + counter);

        System.out.println(webSocket.getRemoteSocketAddress().getAddress()
                .getHostAddress()
                + " 连接上WebSocket服务器  ！,当前连接上来的WebSocket客户端数量为:"+counter);
    }

    @Override
    public void onClose(WebSocket webSocket, int i, String s, boolean b) {
        counter--;
        System.out.println(webSocket.getRemoteSocketAddress().getAddress()
                .getHostAddress()
                + " 断开与WebSocket服务器的连接 ！,当前连接上来的WebSocket客户端数量为:"+counter);

        sendToAll(webSocket.getRemoteSocketAddress().getAddress().getHostAddress()
                + " 断开与WebSocket服务器的连接 ！,当前在线人数为:"+counter);
    }

    /**
     * 接收WebSocket客户端发送的消息
     * @param webSocket
     * @param message
     */
    @Override
    public void onMessage(WebSocket webSocket, String message) {
        System.out.println("接收到["
                + webSocket.getRemoteSocketAddress().getAddress().getHostAddress()
                + "]客户端发送的消息,消息内容是:" + message);
        //将接收到的客户端消息发送给所有的连接客户端
        sendToAll("["
                + webSocket.getRemoteSocketAddress().getAddress().getHostAddress()
                + "]" + message);
    }

    @Override
    public void onError(WebSocket webSocket, Exception e) {
        System.out.println("WebSocket Error:");
        e.printStackTrace();
        if (webSocket != null) {
            webSocket.close();
        }
    }

    /**
     * 给所有的WebSocket客户端发送消息
     * @param message 需要发送的消息
     */
    private void sendToAll(String message) {
        Collection<WebSocket> conns = connections();
        synchronized (conns) {
            for (WebSocket client : conns) {
                client.send(message);
            }
        }
    }

    /**
     * 启动WebSocket服务器
     * @param port 启动WebSocket服务器时使用的端口号
     */
    public static void startServer(int port){
        try {
            ChatServer server = new ChatServer(port);
            server.start();//启动WebSocket服务器
            System.out.println("WebSocket服务器已经启动,等待客户端接入,服务器使用的端口号: " + server.getPort());
        }catch (Exception e){
            System.out.println("WebSocket服务器启动失败,原因是: " + e);
        }

    }

    // 测试
    public static void main(String[] args) throws InterruptedException,
            IOException {
       ChatServer.startServer(8887);
    }
}
